/**
 * Created  on 2018/8/28.
 */
var router = require('express').Router();
var AV = require('leanengine');
var Todo = AV.Object.extend('Todo');
var common = require('../cloud/common');
let moment = require('moment')
let momenttz = require('moment-timezone')
momenttz.locale('zh-cn');
var fs = require('fs');
var uuid = require('node-uuid');
var multiparty = require('multiparty');
var functionTool = require('../queryFun/functionTool');
/**
 * 认证状态
 */
router.post("/verifyStatus",(req,res)=>{
    let userOId=req.currentUser.id
    let query=new AV.Query('Shop_account_verify');
    query.equalTo("userOId",userOId);
    query.first().then(async result=>{
        let returnObj={};

        if(!result){
            returnObj.verifyStatus="4";
        }else{
            let status=result.get("status")
            if("1"==status||""==status||null==status||undefined==status){
                status="1";
            }
            returnObj.verifyStatus=status;
        }
        let shopObj=await functionTool.getShop(userOId);
        let shopOId=""
        if(shopObj){
            shopOId=shopObj.get("objectId")
        }
        returnObj.shopOId=shopOId
        return res.json(common.getReturnArr("1","10000","",returnObj));


    }).catch(error=>{
        callback(error.message,null);
    })
})


router.post('/imgUpload', (req, res) => {
    var form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        if (err) {
            console.log(err)
        } else {
            fs.readFile(files.file[0].path, (error, data) => {
                let key = uuid.v1().replace(/-/g, "") + ".png";
                let file = new AV.File(key, data);
                file.save().then(function (pic) {
                    let returnObj={
                        picUrl:pic.url(),
                        id:pic.id
                    }
                    console.log("imgUpload-->"+JSON.stringify(common.getReturnArr("", 10000, "上传成功", returnObj)))
                    res.json(common.getReturnArr("", 10000, "上传成功", returnObj));
                }, (reject) => {
                    return res.json(common.getErrArr(""));
                })
            })
        }

    });
})

/**
 * 申请认证
 */
router.post("/applyVerify", async function (req, res) {
    let userOId=req.currentUser.id
    let name=req.body.name;//开卡人姓名
    let ic=req.body.ic;//身份证号
    let handleIcPicId=req.body.handleIcPicId;//手持身份证
    let icPositivePicId=req.body.icPositivePicId;//身份证正面照片
    let icNegativePicId=req.body.icNegativePicId;//身份证反面照片
    console.log("name="+name+";ic="+ic+";handleIcPicId="+handleIcPicId+";icPositivePicId="+icPositivePicId+";icNegativePicId="+icNegativePicId)
    if(!name||name=="")
        return res.json(common.getErrArr("参数错误"));

    let tel= await getTel(userOId);

    if(!ic||ic=="")
        return res.json(common.getErrArr("参数错误"));

    if(!handleIcPicId||handleIcPicId=="")
        return res.json(common.getErrArr("参数错误"));

    if(!icPositivePicId||icPositivePicId=="")
        return res.json(common.getErrArr("参数错误"));

    if(!icNegativePicId||icNegativePicId=="")
        return res.json(common.getErrArr("参数错误"));

    tel=tel.toString();
    ic=ic.toString();
    name=name.replace(/s/g, "");
    tel=tel.replace(/s/g, "");
    ic=ic.replace(/s/g, "");
    handleIcPicId=handleIcPicId.replace(/s/g, "");
    icPositivePicId=icPositivePicId.replace(/s/g, "");
    icNegativePicId=icNegativePicId.replace(/s/g, "");
    verifyStatus(userOId,function(error,verifyObj){
        if(error){
            return res.json(common.getErrArr(error));
        }else{
            //修改审核资料
            if(verifyObj!=null){
                if("1"==verifyObj.get("status")||""==verifyObj.get("status")||null==verifyObj.get("status")||undefined==verifyObj.get("status"))
                    return res.json(common.getErrArr("你已经审核通过"));
            }
            var Accountverify=common.getEntity("Shop_account_verify");
            var accountverify = new Accountverify();
            accountverify.set("userOId",userOId);
            accountverify.set("name",name);
            accountverify.set("identityCardNo",ic);
            accountverify.set("tel",tel);
            accountverify.set("holdIdentityCard",{"__type":"Pointer",className:"_File",objectId:handleIcPicId});
            accountverify.set("identityCard1",{"__type":"Pointer",className:"_File",objectId:icPositivePicId});
            accountverify.set("identityCard2",{"__type":"Pointer",className:"_File",objectId:icNegativePicId});

            accountverify.set("status","1");
            accountverify.set("shopStatus","1");
            // return res.json(common.getReturnArr("1","10000","",""));
            accountverify.save().then(result=>{
                return res.json(common.getReturnArr("1","10000","",""));
            }).catch(error=>{
                console.log(error)
                return res.json(common.getErrArr(error));
            })
        }
    });
});

/**
 * 查看是否通过身份验证
 * @param userOId
 * @param callback
 */
function verifyStatus(userOId,callback){
    if(!userOId||userOId==""){
        return callback("错误的参数",null);
    }
    let query=new AV.Query('Shop_account_verify');
    query.equalTo("userOId",userOId);
    query.first().then(result=>{

        callback(null,result);

    }).catch(error=>{
        callback(error.message,null);
    })
}

function getTel(userOId){
    let query=new AV.Query('_User');
    return query.get(userOId).then(result=>{
        return result.get("mobilePhoneNumber")
    }).catch(error=>{
        console.log(error)
        return null
    })
}
router.post("/fetchAllManager", async function (req, res) {
    let userOId=req.currentUser.id
    let shopOId=req.body.shopOId;
    let pageIndex=req.body.pageIndex;
    let pageSize=req.body.pageSize;
    let name=req.body.name;
    let tel=req.body.tel;


    if (shopOId == '' || !shopOId) {
        return res.json(common.getErrArr("参数错误"));
    }
    if (pageIndex == '' || !pageIndex) {
        pageIndex = 1;
    } else {
        pageIndex = parseInt(pageIndex);
    }
    if (pageSize == '' || !pageSize ) {
        pageSize = 20
    } else {
        pageSize = parseInt(pageSize)
    }

    let query=new AV.Query('UserRole');
    if((name&&name!="")||(tel&&tel!="")){
        let userQuery=new AV.Query("_User")
        if(name&&name!=""){
            userQuery.contains("nickName",name)
        }
        if(tel&&tel!=""){
            userQuery.equalTo("mobilePhoneNumber",tel)
        }
        query.matchesQuery("userObj",userQuery)
    }

    query.equalTo("shopOId",shopOId);
    query.include("userObj")
    query.skip((pageIndex - 1) * pageSize);
    query.limit(pageSize);
    query.find().then(result=>{
        query.count().then(async function (count) {
            let returnObj={}
            let resultArr=[]
            for(let item of result){
                let obj={}
                obj.objectId=item.id
                obj.name=item.get("userObj").get("nickName");
                obj.tel=item.get("userObj").get("mobilePhoneNumber");
                resultArr.push(obj)
            }
            returnObj.data=resultArr;
            returnObj.total=count;
            return res.json(common.getReturnArr("1","10000","",returnObj));
        }).catch(error=>{
            console.log(error)
            return res.json(common.getErrArr(error));
        })
    }).catch(error=>{
        console.log(error)
        return res.json(common.getErrArr(error));
    })

})

router.post("/deleteManager", async function (req, res) {
    let objectId=req.body.objectId
    if (objectId == '' || !objectId) {
        return res.json(common.getErrArr("参数错误"));
    }
    let userRole = AV.Object.createWithoutData('UserRole', objectId);
    userRole.destroy().then(success=> {
        return res.json(common.getReturnArr("1","10000","删除成功",""));
    }).catch(error=> {
        console.log(error)
        return res.json(common.getErrArr("删除失败"));
    });
})

router.post("/addManager", async function (req, res) {
    let shopOId=req.body.shopOId
    let userOId=req.body.userOId
    if (shopOId == '' || !shopOId) {
        return res.json(common.getErrArr("参数错误"));
    }
    if (userOId == '' || !userOId) {
        return res.json(common.getErrArr("参数错误"));
    }

    let query = new AV.Query('UserRole');
    query.equalTo("shopOId",shopOId)
    query.equalTo("userOId",userOId)
    query.first().then(result=>{
        if(result){
            return res.json(common.getErrArr("管理员已存在请勿重复添加"));
        }
        let UserRole = AV.Object.extend('UserRole');
        let userRole = new UserRole();
        userRole.set("shopOId",shopOId)
        userRole.set("shopObj", AV.Object.createWithoutData("Shop_shop", shopOId))
        userRole.set("userOId",userOId)
        userRole.set("userObj", AV.Object.createWithoutData("_User", userOId))
        userRole.save().then(result=>{
            return res.json(common.getReturnArr("1","10000","保存成功",""));
        }).catch(error=>{
            console.log(error)
            return res.json(common.getErrArr("保存失败"));
        })
    }).catch(error=>{
        console.log(error)
        return res.json(common.getErrArr("保存失败"));
    })
})

router.post("/searchUser", async function (req, res) {
    let userOId=req.currentUser.id
    let name=req.body.name;
    let tel=req.body.tel;

    if (tel == '' || !tel) {
        tel=""
    }
    let query=new AV.Query('_User');
    if (name&&name!= '') {
        query.equalTo("nickName",name)
    }
    if (tel&&tel!= '') {
        query.equalTo("mobilePhoneNumber",tel)
    }
    query.notContainedIn("objectId",[userOId])

    query.first().then(result=>{
        if(result){
            let obj={}
            obj.objectId=result.get("objectId")
            obj.name=result.get("nickName");
            obj.tel=result.get("mobilePhoneNumber");
            return res.json(common.getReturnArr("1","10000","",[obj]));
        }else{
            return res.json(common.getErrArr("暂无数据"));
        }

    }).catch(error=>{
        console.log(error)
        return res.json(common.getErrArr(error));
    })
})
//获取店铺信息
async function getShopInfo(userOId){
  var query = new AV.Query('Shop_shop');
  // query.equalTo("status",'1');
  query.equalTo("userOId",userOId);
  return query.first().then(shopObj=>{
    return {
      shopOId:shopObj.id,
      shopName:shopObj.get('name')
    }
  }).catch(error=>{
    console.log(error)
  })
}
/**
 * 店铺收益
 */
router.post("/storeIncome", async function (req, res) {
    // let userOId=req.currentUser.id
    // let shopOId=req.body.shopOId;
    // shopOId="5b446f5a67f356003a7c7f69";//测试
    let userOId=req.currentUser.id;
    var shopInfo = await getShopInfo(userOId)
    let shopOId = shopInfo.shopOId
    let pageIndex=req.body.pageIndex;
    let pageSize=req.body.pageSize;
    if(!shopOId||shopOId==""){
        return res.json(common.getErrArr("参数错误！"));
    }
    if (pageIndex == '' || !pageIndex) {
        pageIndex = 1;
    } else {
        pageIndex = parseInt(pageIndex);
    }
    if (pageSize == '' || !pageSize ) {
        pageSize = 20
    } else {
        pageSize = parseInt(pageSize)
    }

    let createrOId=await getShopCreater(shopOId);

    let query=new AV.Query('Shop_account_detail');
    query.equalTo("userOId",createrOId)
    query.equalTo("remark","销售收入")
    query.skip((pageIndex - 1) * pageSize);
    query.limit(pageSize);
    query.descending("createdAt")
    query.find().then(async result=>{
        query.count().then(async count=>{
            if(!result||result.length<=0){
                return res.json(common.getErrArr("暂无数据"));
            }
            let returnObj={}
            let data=[]
            for(let item of result){
                var temObj = {};
                temObj.objectId = item.get("objectId");
                temObj.remark = item.get("remark");//收益类型
                temObj.status =item.get("status");//1正常，0冻结
                temObj.changeMoney = Math.round(item.get("changeMoney") * 100) / 100;
                temObj.changeType = item.get("changeType");
                temObj.refund = item.get("refund");


                let orderNo= item.get("orderNo");
                let shopOrder=await getShopOrder(orderNo)
                if(shopOrder){
                    temObj.totalPrice=shopOrder.get("totalPrice")//总额
                    temObj.fare=shopOrder.get("fare")//运费
                    let extensionDivision=Number(temObj.totalPrice)-Number(temObj.changeMoney);
                    temObj.extensionDivision=Math.round(extensionDivision * 100) / 100;

                    let shopOrderGoods=await getShopOrderGoods(shopOrder.get("objectId"))
                    if(shopOrderGoods){
                        let goodsOId=shopOrderGoods.get("goodsOId")
                        temObj.appUrl="http://health.aladada.com/goods/info?id="+ goodsOId
                        temObj.goodsName=shopOrderGoods.get("goodsName")
                        temObj.goodsPicUrl=shopOrderGoods.get("goodsPicURL")
                        temObj.num=shopOrderGoods.get("num")
                    }
                }
                temObj.createdAt = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }

            returnObj.data=data;
            returnObj.count=count;
            return res.json(common.getReturnArr("1","10000","",returnObj));
        }).catch(error=>{
            console.log(error)
            return res.json(common.getErrArr("暂无数据"));
        })

    }).catch(error=>{
        console.log(error)
        return res.json(common.getErrArr("暂无数据"));

    })
})

function getShopCreater(shopOId){
    let query=new AV.Query('Shop_shop');
    return query.get(shopOId).then(result=>{
        if(!result){
            return false
        }
        return result.get("userOId")
    }).catch(error=>{
        console.log(error)
        return false
    })
}

function getShopOrderGoods(orderOId){
    let query=new AV.Query('Shop_order_goods');
    query.equalTo("orderOId",orderOId)
    return query.first().then(result=>{
        if(!result){
            return false
        }
        return result
    }).catch(error=>{
        console.log(error)
        return false
    })
}
function getShopOrder(orderNo){
    let query=new AV.Query('Shop_order');
    query.equalTo("orderCode",orderNo)
    return query.first().then(result=>{
        if(!result){
            return false
        }
        return result
    }).catch(error=>{
        console.log(error)
        return false
    })
}

/**
 * 店铺收益详情
 */
router.post("/storeIncomeDetail", async function (req, res) {
    let objectId=req.body.objectId;
    if(!objectId||objectId==""){
        return res.json(common.getErrArr("参数错误！"));
    }
    let query=new AV.Query('Shop_account_detail');
    query.get(objectId).then(async result=>{
        if(!result){
            return res.json(common.getErrArr("暂无数据"));
        }

        var temObj = {};
        temObj.objectId = result.get("objectId");
        temObj.remark = result.get("remark");//收益类型
        temObj.status =result.get("status");//1正常，0冻结
        temObj.changeMoney = Math.round(result.get("changeMoney") * 100) / 100;
        temObj.changeType = result.get("changeType");
        temObj.refund = result.get("refund");
        temObj.orderCode = result.get("orderNo");

        let shopOrder=await getShopOrder(temObj.orderCode)
        if(shopOrder){

            temObj.totalPrice=shopOrder.get("totalPrice")//总额
            temObj.fare=shopOrder.get("fare")//运费
            let extensionDivision=Number(temObj.totalPrice)-Number(temObj.changeMoney);
            temObj.extensionDivision=Math.round(extensionDivision * 100) / 100;

            temObj.receiver=shopOrder.get("receiver")
            temObj.phone=shopOrder.get("phone")
            temObj.address=shopOrder.get("address")
            temObj.expressCode=shopOrder.get("expressCode")
            temObj.logisticsCom=shopOrder.get("logisticsCom")
            temObj.deliverTime=moment(shopOrder.get("deliverTime")).format('YYYY年MM月DD HH:mm:ss')
            temObj.orderCreatedAt=moment(shopOrder.get("createdAt")).format('YYYY年MM月DD HH:mm:ss')
            temObj.orderPayTime=moment(shopOrder.get("payTime")).format('YYYY年MM月DD HH:mm:ss')
            temObj.payType=shopOrder.get("payType")

            let shopOrderGoods=await getShopOrderGoods(shopOrder.get("objectId"))
            if(shopOrderGoods){
                let goodsOId=shopOrderGoods.get("goodsOId")
                temObj.appUrl="http://health.aladada.com/goods/info?id="+ goodsOId
                temObj.goodsName=shopOrderGoods.get("goodsName")
                temObj.goodsPicUrl=shopOrderGoods.get("goodsPicURL")
                temObj.num=shopOrderGoods.get("num")
            }
        }
        temObj.createdAt = moment(result.createdAt).format('YYYY年MM月DD HH:mm:ss');
        return res.json(common.getReturnArr("1","10000","",temObj));
    }).catch(error=>{
        console.log(error)
        return res.json(common.getErrArr("暂无数据"));
    })
})

module.exports = router;